<?php

	include_once '../controladores/ControladorAplicaciones.php';
	include_once '../controladores/ControladorUsuarios.php';
	include_once '../controladores/ControladorImagenes.php';	
	include_once "../config.inc.php";
	include_once '../controladores/ControladorElementos.php';
	
	if (!empty($_GET['usr']) && !empty($_GET['app']) && !empty($_GET['sec'])){
			$usr = $_GET['usr'];
			$app = $_GET['app'];
			$secc = $_GET['sec'];
	}
	
	$command = new ControladorElementos(GALLERY_ELEMENT);
	$orderNewElement = $command->obtainOrderNewElement($app,$secc) + 1;
	$command->createElement(array("sec_id" => $secc,"element_order" => $orderNewElement));	
	
	$galleryId = $command->obtainIdGalleryImages($app,$secc);
	
	// Obteniendo datos del usuario, nada que ver con insercion de elementos.
	
	$command = new ControladorAplicaciones();	
	$appName = $command->searchApplicationName($app);
	
	$command = new ControladorUsuarios();
	$userEmail = $command->obtainUserEmail($usr);

	$targetApplication = ROUTE_APPLICATIONS_USERS.$userEmail."/Applications/".$appName;
	$targetApplicationImages = $targetApplication."/images";
	
	$nameFile = $_FILES['files']["name"];
	$targets = array();	
	$ids = array();	
		
		for ($i=0; $i < count($nameFile); $i++){		
			
			$command = new ControladorImagenes();	
			$im = $command->searchImageId(basename($nameFile[$i]));
		    $targets[$i] = $targetApplicationImages."/".basename($nameFile[$i]); 
			
			  if (strlen($im) == 0){
				  
			    $command->createImage(basename($nameFile[$i]));
				$im = $command->searchImageId(basename($nameFile[$i]));
				$ids[$i] = $im;								
				
			  }
			  else{ 
			  
				$im = $command->searchImageId(basename($nameFile[$i]));
				$ids[$i] = $im;								
				
			  }
		}

    $locations = array();
	
	  $tmpLocations = $_FILES['files']["tmp_name"];		
							
		for ($i=0; $i < count($tmpLocations); $i++) 
				$locations[$i] =  $tmpLocations[$i];

	//---------------------------------------------------------------------------------------------
	
	$command = new ControladorElementos(IMAGE_ELEMENT);
		
	  for ($i=0; $i < count($locations); $i++){
		if (move_uploaded_file($locations[$i],$targets[$i])){
			$command->createElement(array("image_id" => $ids[$i],"sec_id" => $secc,"element_order" => ($i+1),"ie_link_to" => "","gallery_id" => $galleryId));
		}
	  }
	  
	  header("Location:section_elements.php?usr=".$usr."&app=".$app."&sec=".$secc."");
?>